/**
 * @format
 * @Author: TC
 * @Date: 2021-09-26 14:16:58
 * @Last Modified by:   TC
 * @Last Modified time: 2021-09-26 14:16:58
 */

import { EventTouch, Node, _decorator } from "cc";
import { app } from "../../FrameWork/App";
import { BaseComponent } from "../../FrameWork/Module/Component/BaseComponent";

const { ccclass, property } = _decorator;
declare const h5api: any;
@ccclass("BaseAdBtn")
export class BaseAdBtn extends BaseComponent {
    @property(Node)
    rootNode: Node = null;
    @property(Node)
    tipNode: Node = null;
    @property(Node)
    tomorrowTxt: Node = null;

    //初始化一些数据和UI
    protected init(): void {
        super.init();
        this.node.active = false;
        this.updateState();
    }

    //添加监听
    protected addEvent(): void {
        super.addEvent();
        this.node.on(Node.EventType.TOUCH_END, this.onClickAd, this);
    }

    //移除监听
    protected removeEvent(): void {
        this.node.off(Node.EventType.TOUCH_END, this.onClickAd, this);
    }

    protected onClickAd(e: EventTouch): void {
        if (!app.sdkMgr.isPlatForm()) {
            this.onAdSucc();
            return;
        }
        h5api.playAd((obj: any) => {
            console.log("代码:" + obj.code + ",消息:" + obj.message);
            if (obj.code === 10000) {
                console.log("开始播放");
            } else if (obj.code === 10001) {
                console.log("播放结束");
                this.onAdSucc();
                this.updateState();
            } else {
                console.log("广告异常");
                app.windowMgr.showTip("广告播放异常");
            }
        });
    }

    //广告成功播放回调
    protected onAdSucc(): void {}

    protected updateState(): void {
        if (!app.sdkMgr.isPlatForm()) {
            this.show();
            return;
        }
        h5api.canPlayAd((data: any) => {
            console.log("是否可播放广告", data.canPlayAd, "剩余次数", data.remain);
            if (data.canPlayAd && data.remain > 0) this.show();
            else this.hide();
        });
    }

    protected show(): void {
        this.node.active = true;
        if (this.tipNode) this.tipNode.active = true;
        if (this.tomorrowTxt) this.tomorrowTxt.active = false;
    }

    protected hide(): void {
        this.node.active = false;
        if (this.tomorrowTxt) this.tomorrowTxt.active = true;
    }
}
